import {
    specslist,
    specscount
} from "../../http/api"
const state = {
    list:[],
    total:0,
    size:2,
    page:1
}

const getters = {
    list(state){
        return state.list
    },
    total(state){
        return state.total
    },
    size(state){
        return state.size
    },
    page(state){
        return state.page
    },
}

const mutations = {
    changeList(state,list){
        state.list=list;
    },
    changetotal(state, total) {
        state.total = total;
    },
    changesize(state, size) {
        state.size = size;
    },
    changepage(state, page) {
        state.page = page;
    }
}

const actions = {
    //逻辑
    reqListTwo(context){
        context.dispatch("reqList");

        //请求总数
        specscount().then(res=>{
            if(res.data.code==200){
                //修改总数
                context.commit("changetotal",res.data.list[0].total);
            }
        })
    },

    reqList(context,isAll=false){
        let params = isAll ? {}:{page: context.state.page, size: context.state.size};
        specslist(params).then(res=>{
            if(res.data.code==200){
                let arr=res.data.list ? res.data.list : []
                //如果请到的是空数组，并且不是第一页，page-1，再次请求列表(不能page--，直接修改)
                if(arr.length==0&&context.state.page>1){
                    context.commit("changepage",context.state.page-1);
                    context.dispatch("reqList");
                    return;
                }
                context.commit("changeList",arr);
            }
        })
    },

    changePage(context,page){
        context.commit("changepage",page);
        //重新请求列表
        context.dispatch("reqList");
    }
    
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}